﻿using System;
using System.Collections.Generic;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Tool.hbm2ddl;
using NHibernate.Linq;
using System.Linq;

namespace CsharpTrainer.NHibernate3
{
    public class NHibernateDb<TMap> : IDisposable
    {
        private string connString;
        private ISessionFactory sessFactory;
        
        public ISessionFactory SessionFactory
        {
            get { return sessFactory; }
            set { sessFactory = value; }
        }

        public void Dispose()
        {
            sessFactory.Dispose();
        }

        public NHibernateDb(string pStr)
        {
            connString = pStr;
            sessFactory = CreateSessionFactory();
        }

        ~NHibernateDb()
        {
            try
            {
                Dispose();
            }
            catch 
            {
                Console.WriteLine("Exception: session factory dispose failed!");
            }
        }

        private ISessionFactory CreateSessionFactory()
        {
            return Fluently.Configure()
                .Database(MsSqlConfiguration
                              .MsSql2008
                              .ConnectionString(connString))
                .Mappings(m => m.FluentMappings
                                   .AddFromAssemblyOf<TMap>())
                .BuildSessionFactory();
        }
        
        private void CreateSchema(Configuration cfg)
        {
            var schemaExport = new SchemaExport(cfg);
            schemaExport.Drop(false, true);
            schemaExport.Create(false, true);
        }

        public void CreateDatabase()
        {
            Fluently.Configure()
                .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connString))
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<TMap>())
                .ExposeConfiguration(CreateSchema)
                .BuildConfiguration();
        }
    }
}
